package com.jmp.sms;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.google.common.collect.Lists;
import com.jmp.base.dto.SmsCodeEnums;
import lombok.extern.slf4j.Slf4j;
import one.stand.util.AssertUtil;
import one.stand.util.OneListUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.annotation.Async;

import java.util.List;
import java.util.Objects;

@Slf4j
public class DefaultSmsClient implements SmsClient {
    private SmsProperties.OneSms smsProperties;
    private SmsProperties.TemplateCode templateCodeProperties;

    public DefaultSmsClient(SmsProperties.TemplateCode templateCode, SmsProperties.OneSms smsProperties) {
        this.templateCodeProperties = templateCode;
        this.smsProperties = smsProperties;
    }

    @Override
    public String getAppId() {
        return this.smsProperties.getAppId();
    }

    /**
     * 短信验证码
     */
//    @Async("asyncServiceExecutor")
    public void sendSmsCode(SmsClientCodeRequest request) {
        sendSms(request.getPhone(), request.getType(), "{number:\"" + request.getCode() + "\"}");
    }

    /**
     * 批量发送相同内容
     */
    @Async("asyncServiceExecutor")
    public void sendBatchSms(List<String> phones, Integer type, String params) {
        if (OneListUtil.isEmpty(phones) || Objects.isNull(type)) {
            log.warn("phones or type is null");
            return;
        }

        if (phones.size() <= 1000) {
            sendSms(String.join(",", phones), type, params);
        } else {
            List<String> list = Lists.newArrayListWithExpectedSize(100);
            for (String phone : phones) {
                list.add(phone);
                if (list.size() == 1000) {
                    sendSms(String.join(",", phones), type, params);
                    list = Lists.newArrayListWithExpectedSize(100);
                }
            }
        }
    }

    private void sendSms(String phone, Integer type, String param) {
        DefaultProfile profile = DefaultProfile.getProfile("default", smsProperties.getAccountKeyId(), smsProperties.getAccessKeySecret());
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest commonRequest = new CommonRequest();
        commonRequest.setMethod(MethodType.POST);
        commonRequest.setDomain("dysmsapi.aliyuncs.com");
        commonRequest.setVersion("2017-05-25");
        commonRequest.setAction("SendSms");
        SmsCodeEnums smsCodeEnums = SmsCodeEnums.getByCode(type);
        commonRequest.putBodyParameter("PhoneNumbers", phone);
        commonRequest.putBodyParameter("TemplateCode", getTemplateCode(smsCodeEnums));
        commonRequest.putBodyParameter("TemplateParam", param);
        commonRequest.putBodyParameter("SignName", StringUtils.defaultIfBlank(smsCodeEnums.getSign(), smsProperties.getSignName()));
        try {
            CommonResponse response = client.getCommonResponse(commonRequest);
            log.info("短信发送结果：{}", response.getData());
        } catch (Exception e) {
            log.error("短信发送异常：{}", e.getMessage());
        }
    }

    private String getTemplateCode(SmsCodeEnums smsCodeEnums) {
        String templateCode = null;
        switch (smsCodeEnums) {
            case login_sms:
            case login_sms_jxs:
                templateCode = templateCodeProperties.getLoginSms();
                break;
            case join_company:
                templateCode = templateCodeProperties.getJoinCompany();
                break;
            case unread_msg:
                templateCode = templateCodeProperties.getUnreadMsg();
                break;
            case jxsSign:
                templateCode = templateCodeProperties.getJxsSign();
                break;
            case jxsTicketSave:
                templateCode = templateCodeProperties.getJxsTicketSave();
                break;
            case jxsSignSuccess:
                templateCode = templateCodeProperties.getJxsSignSuccess();
                break;
            case jxsSignFail:
                templateCode = templateCodeProperties.getJxsSignFail();
                break;
            case jxsSignSuccessSupplier:
                templateCode = templateCodeProperties.getJxsSignSuccessSupplier();
                break;
            case jxsSignFailSupplier:
                templateCode = templateCodeProperties.getJxsSignFailSupplier();
                break;
        }
        AssertUtil.nonNull(templateCode, "短信模板Code未配置");
        return templateCode;
    }
}
